package com.horse.cloud.framework.base;

import com.horse.cloud.framework.base.callback.DoTransactionContent;
import com.horse.cloud.framework.general.enums.ResponseCodeEnums;
import com.horse.cloud.framework.general.response.Response;
import com.horse.cloud.framework.redis.RedisClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * @create : Created by intelliJ IDEA 17.2
 * @author : bing.Pan
 * @e-mail : 15923508369@163.com
 * @gmdate : 11 13 2017 13:47
 * @sidesc :
 */
public class BaseService {


    protected static final Logger LOGGER = LoggerFactory.getLogger(BaseService.class);

    @Autowired protected TransactionTemplate transactionTemplate;
    @Autowired protected RedisClient redisClient;


    /**
     * TransactionTemplate 编程式事物基类
     * 统一事物执行基类,解决大事物代码，拆分大事物，对业务层方法需要事物支持的代码进行精准控制
     * 为所有需要事物执行的方法提供通用的事物执行器，具体业务代码无需关注事物开启、异常回滚，提交
     * 示例:
     *  return withTransaction(new DoTransactionContent() {
     *             @Override
     *             public Response execute() throws Exception {
     *                  //具体业务逻辑
     *             }
     *         }.logTitle("测试事物").logMethod("testTransaction").logArgs(new Response<>()).recordTransactionContentLog());
     *
     * @param doTransactionContent {@link DoTransactionContent}   手动事物回调执行方法抽象类
     * @return Response {@link Response} 事物执行后的结果参数，
     */
    protected Response withTransaction(final DoTransactionContent doTransactionContent){

        Object execute = transactionTemplate.execute((TransactionCallback<Object>) transactionStatus -> {
            try {
                Response exec = doTransactionContent.execute();
                transactionStatus.flush();
                return exec;
            } catch (Exception e) {
                transactionStatus.setRollbackOnly();
                LOGGER.error("【framework-base】 事物执行异常",e);
                return new Response(ResponseCodeEnums.DATA_TRANSACTION_ROLL_BACK);
            }
        });
        return (Response) execute;
    }
}
